package com.btkjgc.service.impl;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;

import com.btkjgc.models.AdminUser;
import com.btkjgc.models.AdminUserRole;
import com.btkjgc.models.AjaxObj;
import com.btkjgc.models.Dictionary;
import com.btkjgc.models.Role;
import com.btkjgc.models.extend.AdminUserModel;
import com.btkjgc.service.intf.AdminUserManageService_Intf;
import com.btkjgc.utils.HibernateUtil;

/**
 * Created by _ESE on 2015/2/9.
 */
@Component
public class AdminUserManageService_Impl extends BaseService_Impl implements AdminUserManageService_Intf
{

	static Logger logger = Logger.getLogger(AdminUserManageService_Impl.class);
 

 
	@SuppressWarnings("unchecked")
	@Override
	public Integer insertAdminUser(AdminUserModel adminUserModel)
	{
		List<AdminUser> judgeUserList = HibernateUtil.executeQueryList(
				"FROM AdminUser where loginname = ? and del=0",
				new String[] { adminUserModel.getLoginname() });
		if (judgeUserList.size() > 0) { return -2; }

		AdminUser adminUser = new AdminUser();

		try {
			PropertyUtils.copyProperties(adminUser, adminUserModel);
			HibernateUtil.save(adminUser);
		
			//插入role，admin_user_role
			String roleString = "from Role where id=?";
			String[] roleparam = new String[] { adminUserModel.getRoleId()
					.toString()};
	 
			Role role = (Role) HibernateUtil.executeQueryOneObject(roleString,
					roleparam);
			if (role != null) {
				String auhql = "FROM AdminUser where loginname=? and del=0";
				AdminUser au = (AdminUser) HibernateUtil.executeQueryOneObject(
						auhql, new String[] { adminUserModel.getLoginname() });
				AdminUserRole adminUserRole = new AdminUserRole();
				adminUserRole.setUserid(au.getId());
				adminUserRole.setRoleid(role.getId());
				HibernateUtil.save(adminUserRole);
				return 1;
			}

		} catch (Exception e) {
			return -11;
		}
		return -1;
	}

	@Override
	public void deleteById(Integer adminUserId)
	{
		List hqlList=new ArrayList<>();
		String hql = "update from AdminUser set del=1 where id=?";
		hqlList.add(hql);
	
		String hql2 = "delete FROM AdminUserRole where userid = ?";
		hqlList.add(hql2);
		
		
		List paramLists=new ArrayList<>();
		List paramLists2 =new ArrayList<>();
		paramLists2.add(String.valueOf(adminUserId));
		paramLists.add(paramLists2);
		paramLists.add(paramLists2);
		HibernateUtil.batchExecuteUpdate(hqlList, paramLists);
		 
	}

 

	@Override
	public void updateAdminUserRole(int adminUserId, int roleid)
	{
		String hql = "FROM Role where id=?";
		Role role = (Role) HibernateUtil.executeQueryOneObject(hql,
				new String[] { roleid+"" });
 
 
			hql = "delete from AdminUserRole where  userid=?";
			String param1[] = { String.valueOf(adminUserId) };
			HibernateUtil.executeUpdate(hql, param1);
	 
			hql = "insert into admin_user_role_t(roleid,userid) values(?,?)";
			String param2[] = { role.getId().toString(), String.valueOf(adminUserId) };
			HibernateUtil.executeSQLUpdate(hql, param2);
	 
		


	}

 
	@Override
	public void setListData(HttpServletRequest request,ModelAndView mv,int pageIndex, int totalRecord,
			List<AdminUserModel> adminUserList) {
		// TODO Auto-generated method stub
		
		AdminUser adminUser = (AdminUser) request.getSession().getAttribute("user");


		Enumeration<String> names = request.getParameterNames();
		while (names.hasMoreElements())
		{
			String name = names.nextElement();
			mv.addObject(name, request.getParameter(name));
		}
 
		
		mv.addObject("user_info", adminUser);
		mv.addObject("admin_users", adminUserList);
		
		
		String hqllevel = "FROM Role where id in (select roleid from AdminUserRole where userid = ?)";
		List<Role> adminLevelList = HibernateUtil.executeQueryList(hqllevel,
				new String[] { adminUser.getId() + "" });
		if (adminLevelList.size() > 0)
		{
			Role adminLevel = adminLevelList.get(0);
			String hqlrole = "from Role where id>? AND level<=? And del=0";
			List<Role> rolelist = HibernateUtil.executeQueryList(hqlrole,
					new String[] { "0", adminLevel.getLevel() + "" });
			mv.addObject("rolelist", rolelist);
		}
	 
		
		String sql = " select aut.name,CONCAT(2,'-',id) 'key' from account_user_t aut where aut.type=1 and aut.del = 0\n" +
				"union all\n" +
				" select pct.name,CONCAT(1,'-',id) 'key'  from property_company_t pct where pct.del = 0 ";
		
		List<Dictionary> companyList = HibernateUtil.executeSQLQueryList(sql,Dictionary.class);
		if (companyList.size() > 0)
		{
			mv.addObject("companyList", companyList);
		}
  

		mv.addObject("currentpage", pageIndex);
		mv.addObject("totalRecord", totalRecord);
	}




	@Override
	public AjaxObj updateAdminUser(AdminUserModel adminUserModel) {
		// TODO Auto-generated method stub
 
		AjaxObj ajaxObj=new AjaxObj();
		ajaxObj.setResult(true);
		
		String hql=" update from AdminUser " +
				   " set" +
				   " phone='"+adminUserModel.getPhone()+"',"+
				   " email='"+adminUserModel.getEmail()+"',"+
				   " loginname='"+adminUserModel.getLoginname()+"',"+
				   " username='"+adminUserModel.getUsername()+"',"+
				   " companyid="+Integer.valueOf(adminUserModel.getCompanyStr().split("-")[1])+","+
				   " companytype="+Integer.valueOf(adminUserModel.getCompanyStr().split("-")[0])+","+
				   " provinceid="+adminUserModel.getProvinceid()+","+
				   " cityid="+adminUserModel.getCityid()+","+
				   " operdate=now()"+
				   " where id="+adminUserModel.getId();
		     
		try {
			HibernateUtil.executeUpdate(hql);
			updateAdminUserRole(adminUserModel.getId(),adminUserModel.getRoleId());
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			ajaxObj.setResult(false);
			ajaxObj.setMsg("更新时发生错误");
		}
		

		return ajaxObj;
	}

 
 
}
